package com.futvan.z.framework.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.StringReader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.framework.core.z;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
public class FileUtil {

	// 缓存文件头信息-文件头信息 
	public static final HashMap<String, String> AllFileTypes = new HashMap<String, String>(); 
	static { 
		// images 
		AllFileTypes.put("FFD8FF", "jpg"); 
		AllFileTypes.put("89504E47", "png"); 
		AllFileTypes.put("47494638", "gif"); 
		AllFileTypes.put("49492A00", "tif"); 
		AllFileTypes.put("424D", "bmp"); 
		//其它文件
		AllFileTypes.put("41433130", "dwg"); // CAD 
		AllFileTypes.put("38425053", "psd"); 
		AllFileTypes.put("7B5C727466", "rtf"); // 日记本 
		AllFileTypes.put("3C3F786D6C", "xml"); 
		AllFileTypes.put("68746D6C3E", "html"); 
		AllFileTypes.put("44656C69766572792D646174653A", "eml"); // 邮件 
		AllFileTypes.put("D0CF11E0", "doc"); 
		AllFileTypes.put("D0CF11E0", "xls");//excel2003版本文件 
		AllFileTypes.put("5374616E64617264204A", "mdb"); 
		AllFileTypes.put("252150532D41646F6265", "ps"); 
		AllFileTypes.put("255044462D312E", "pdf"); 
		AllFileTypes.put("504B0304", "docx"); 
		AllFileTypes.put("504B0304", "xlsx");//excel2007以上版本文件 
		AllFileTypes.put("52617221", "rar"); 
		AllFileTypes.put("57415645", "wav"); 
		AllFileTypes.put("41564920", "avi"); 
		AllFileTypes.put("2E524D46", "rm"); 
		AllFileTypes.put("000001BA", "mpg"); 
		AllFileTypes.put("000001B3", "mpg"); 
		AllFileTypes.put("6D6F6F76", "mov"); 
		AllFileTypes.put("3026B2758E66CF11", "asf"); 
		AllFileTypes.put("4D546864", "mid"); 
		AllFileTypes.put("1F8B08", "gz"); 
	} 

	public static void main(String[] args) throws Exception {
		Result r = AnalysisOFD("d:/999.ofd");
		System.out.println(r.getData().toString());
	}
	
	/**
	 * 计算文件大小
	 * @param f
	 * @return
	 */
	public static String CalculateFileSize(File f) {
		String size = "";
		if(z.isNotNull(f) && f.isFile()){
			if(f.length()<=1048576) {
				size = String.valueOf(f.length()/1024)+"K";
			}else if(f.length()>1048576 && f.length()<=1073741824) {
				size = String.valueOf(f.length()/1024/1024)+"M";
			}else if(f.length()>1073741824){
				size = String.valueOf(f.length()/1024/1024/1024)+"G";
			}
		}
		return size;
	}
	
	/**
     * 通过文件路径直接修改文件名
     *
     * @param filePath    需要修改的文件的完整路径
     * @param newFileName 需要修改的文件的名称
     * @return
     */
    public static boolean RenameFileName(String filePath, String newFileName) {
    	boolean isok = false;
        File f = new File(filePath);
        if (!f.exists()) { // 判断原文件是否存在（防止文件名冲突）
            return isok;
        }
        newFileName = newFileName.trim();
        if ("".equals(newFileName) || newFileName == null) // 文件名不能为空
            return isok;
        String newFilePath = null;
        if (f.isDirectory()) { // 判断是否为文件夹
            newFilePath = filePath.substring(0, filePath.lastIndexOf("\\")) + "\\" + newFileName;
        } else {
        	if(newFileName.indexOf(".")>=0) {
        		//修改文件扩展名
        		 newFilePath = filePath.substring(0, filePath.lastIndexOf("\\")) + "\\" + newFileName;
        	}else {
        		//只修改文件
        		newFilePath = filePath.substring(0, filePath.lastIndexOf("\\")) + "\\" + newFileName + filePath.substring(filePath.lastIndexOf("."));
        	}
        }
        File nf = new File(newFilePath);
        try {
        	isok = f.renameTo(nf); // 修改文件名
        } catch (Exception err) {
            err.printStackTrace();
            return isok;
        }
        return isok;
    }
    
    /**
     * 解析OFD发票文件
     * @param ofd_path
     * @return
     * @throws Exception
     */
	public static Result AnalysisOFD(String ofd_path) throws Exception {
		Result result = new Result();
		HashMap<String,String> map = new HashMap<String, String>();
		if(z.isNotNull(ofd_path)) {
			File ofd = new File(ofd_path);
			if(z.isNotNull(ofd) && ofd.isFile()) {
				String eName = ofd.getName().substring(ofd.getName().lastIndexOf(".")+1).toLowerCase();
				if(eName.equals("ofd")) {
					String name = ofd.getName().substring(0, ofd.getName().lastIndexOf("."));
					
					//解压缩
					new ZipFile(ofd_path).extractAll("/"+name);
					
					File ofd_xml = new File(ofd.getParent()+"/"+name+"/OFD.xml");
					if(z.isNotNull(ofd_xml) && ofd_xml.isFile()) {
						
						String xml = readFileTXT(ofd_xml.getPath(),"utf-8");
						DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
						DocumentBuilder db = dbf.newDocumentBuilder();

						StringReader sr = new StringReader(xml);
						InputSource is = new InputSource(sr);

						Document document = db.parse(is);
						Node node = document.getDocumentElement().getFirstChild().getFirstChild().getLastChild();
						NodeList list = node.getChildNodes();
						for (int i = 0; i < list.getLength(); i++) {
							Node item = list.item(i);
							if (item.getNodeType() == Node.ELEMENT_NODE) {
								map.put(item.getAttributes().getNamedItem("Name").getNodeValue(), item.getTextContent().trim());
							}
						}
						
						result.setCode(Code.SUCCESS);
						result.setData(map);
					}else {
						result.setCode(Code.ERROR);
						result.setMsg("解析OFD文件XML出错");
					}
					
				}else {
					result.setCode(Code.ERROR);
					result.setMsg("目标文件不是OFD文件");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("未找到OFD文件");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("ofd_path is null");
		}
		return result;
	}

	/**
	 * 判读是否是图片文件
	 * @param filepath 文件路径
	 * @return
	 */
	public static boolean isImage(String filepath) {
		boolean result = false;
		File f = new File(filepath);
		if(f.isFile()) {
			String headerInfo = getFileHeader(filepath);
			String header = AllFileTypes.get(headerInfo);
			if("jpg".equals(header) || "png".equals(header) ||"gif".equals(header) || "tif".equals(header)) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 读取文件头信息
	 * @param filePath
	 * @return
	 */
	private static String getFileHeader(String filePath) { 
		FileInputStream is = null; 
		String value = null; 
		try { 
			is = new FileInputStream(filePath); 
			byte[] b = new byte[4]; 
			is.read(b, 0, b.length); 

			//byte[] --> String
			StringBuilder builder = new StringBuilder(); 
			if (b != null && b.length>0) { 
				String hv; 
				for (int i = 0; i < b.length; i++) { 
					// 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写 
					hv = Integer.toHexString(b[i] & 0xFF).toUpperCase(); 
					if (hv.length() < 2) { 
						builder.append(0); 
					} 
					builder.append(hv); 
				} 
				//设置返回值
				value = builder.toString();
			} 
		} catch (Exception e) {

		} finally { 
			if (null != is) { 
				try { 
					is.close(); 
				} catch (IOException e) { 
				} 
			} 
		} 
		return value; 
	} 

	/**
	 * byte[] -->  String
	 * @param src
	 * @return
	 */
	private static String bytesToHexString(byte[] src) { 
		StringBuilder builder = new StringBuilder(); 
		if (src == null || src.length <= 0) { 
			return null; 
		} 
		String hv; 
		for (int i = 0; i < src.length; i++) { 
			// 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写 
			hv = Integer.toHexString(src[i] & 0xFF).toUpperCase(); 
			if (hv.length() < 2) { 
				builder.append(0); 
			} 
			builder.append(hv); 
		} 
		return builder.toString(); 
	} 

	/**
	 * 获取文件MD5码，如果出错返回为空
	 * @param path
	 * @return MD5
	 */
	public static String getFileMD5(String path) {
		String result = "";
		try {
			if(z.isNotNull(path)) {
				File fpath = new File(path);
				result = DigestUtils.md5Hex(new FileInputStream(fpath));
			}
		} catch (Exception e) {
		}
		return result;
	}
	/**
	 * 将图片流读出为图片
	 * 
	 * @param inputStream
	 * @param path
	 */
	private static void readBlob(InputStream inputStream, String path,String filename) {
		try {
			//判断目录是否存在，如果不存在自动创建
			mkdirs(path);
			FileOutputStream fileOutputStream = new FileOutputStream(path+filename);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, len);
			}
			inputStream.close();
			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 * 创建目录
	 * @param path
	 */
	public static String mkdirs(String path){
		File dir = new File(path);
		// 判断文件目录是否存在
		if (!dir.exists() && !dir.isDirectory()) {
			//自动创建多级目录
			dir.mkdirs();
		}
		return dir.getAbsolutePath();
	}

	/**
	 * 判读目标是否为空
	 * @param path
	 * @return
	 */
	public static boolean dirsIsNull(String path) {
		boolean result = false;
		if(z.isNotNull(path)) {
			File file = new File(path);
			//判读是否是目录
			if(file.isDirectory()){
				if(file.list().length<=0){
					result = true;
				}
			}
		}
		return result;
	}

	/**
	 * 创建文件(文本类)
	 * 
	 * @param FilePath
	 *            文件全路径
	 * @param TXTvalue
	 *            文本内容
	 * @throws Exception
	 */
	public static void createrTXT(String FilePath, String TXTvalue)throws Exception {
		if ("".equals(FilePath) || FilePath == null) {
			return;
		}
		File file = new File(FilePath);
		// 如果找到相同的文件，执行删除
		if (file.exists() && file.isFile()) {
			file.delete();
		}
		file.createNewFile();
		if (!"".equals(TXTvalue) && TXTvalue != null) {
			writeTXT(FilePath, TXTvalue, "");
		}
	}

	/**
	 * 打开文件
	 * 
	 * @param FilePath
	 *            文件路径
	 * @throws Exception
	 */
	public static void OpenFile(String FilePath) throws Exception {
		Runtime.getRuntime().exec(
				"cmd /c start \"\" \""
						+ FilePath.replaceAll("\\\\", "\\\\\\\\") + "\"");
	}

	/**
	 * 文本文件写入信息
	 * 
	 * @param FilePath
	 * @param value
	 * @throws Exception
	 */
	public static void writeTXT(String FilePath, String value, String encoding)throws Exception {
		File f = new File(FilePath);
		if (!f.exists()) {
			f.createNewFile();
		}
		if ("".equals(encoding) || encoding == null) {
			encoding = "UTF-8";
		}
		OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), encoding);
		BufferedWriter writer = new BufferedWriter(write);
		writer.write(value);
		writer.close();
	}


	/**
	 * 获取文件文本信息
	 * 
	 * @param filePath
	 *            路径
	 * @param encoding
	 *            编码格式 GBK UTF-8 GB2312
	 * @return StringBuffer
	 * @throws Exception
	 */
	public static String readFileTXT(String filePath, String encoding) throws Exception {
		StringBuffer returnvalue = new StringBuffer();
		if ("".equals(encoding) || encoding == null) {
			encoding = "UTF-8";
		}
		File file = new File(filePath);
		if (file.isFile() && file.exists()) { // 判断文件是否存在
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					file), encoding);
			BufferedReader bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				returnvalue.append(lineTxt);
			}
			read.close();
		}
		return returnvalue.toString();
	}

	/**
	 * 数据压缩
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 * 
	 * 
	 *             实例： String inputStr =
	 *             "owolf@zlex.orgzlex@zlex.org,snowolf@zlex.org,zlex.snowolf@zlex.org"
	 *             ;
	 * 
	 *             System.err.println("压缩前:\t" + inputStr); byte[] input =
	 *             inputStr.getBytes(); System.err.println("压缩前长度:\t" +
	 *             input.length);
	 * 
	 * 
	 *             System.err.println(); byte[] data = FileUtil.compress(input);
	 *             System.err.println("压缩后长度:\t" + data.length);
	 *             System.err.println();
	 * 
	 *             byte[] output = FileUtil.decompress(data); String outputStr =
	 *             new String(output); System.err.println("解压后:\t" + outputStr);
	 *             System.err.println("解压后长度:\t" + output.length);
	 * 
	 * 
	 * 
	 */
	public static byte[] compress(byte[] data) throws Exception {
		byte[] output = null;
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		// 压缩
		GZIPOutputStream gos = new GZIPOutputStream(baos);
		int count;
		byte dataByte[] = new byte[data.length];
		while ((count = bais.read(dataByte, 0, data.length)) != -1) {
			gos.write(dataByte, 0, count);
		}
		gos.finish();
		gos.flush();
		gos.close();

		output = baos.toByteArray();
		baos.flush();
		baos.close();
		bais.close();
		return output;
	}

	/**
	 * 数据解压缩
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static byte[] decompress(byte[] data) throws Exception {
		byte[] output = null;
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		// 解压缩
		GZIPInputStream gis = new GZIPInputStream(bais);
		int count;
		byte dataByte[] = new byte[data.length];
		while ((count = gis.read(dataByte, 0, data.length)) != -1) {
			baos.write(dataByte, 0, count);
		}
		gis.close();

		output = baos.toByteArray();

		baos.flush();
		baos.close();

		bais.close();
		return output;
	}

	/**
	 * 遍历文件夹
	 * @param path 目录
	 * @return List<String>
	 */
	public static List<File> getPathFiles(String path) {
		List<File> files = new ArrayList<File>();
		return getFiles(path,files,false,null);
	}
	/**
	 * 遍历文件夹
	 * @param path 目录
	 * @param extension 文件扩展名 
	 * @return List<String>
	 */
	public static List<File> getPathFiles(String path,String extension) {
		List<File> files = new ArrayList<File>();
		return getFiles(path,files,false,extension);
	}
	/**
	 * 遍历文件夹【查看下级文件夹】
	 * @param path 目录
	 * @return List<String>
	 */
	public static List<File> getPathAllFiles(String path) {
		List<File> files = new ArrayList<File>();
		return getFiles(path,files,true,null);
	}
	/**
	 * 遍历文件夹【查看下级文件夹】
	 * @param path 目录
	 * @param extension 文件扩展名 
	 * @return List<String>
	 */
	public static List<File> getPathAllFiles(String path,String extension) {
		List<File> files = new ArrayList<File>();
		return getFiles(path,files,true,extension);
	}
	private static List<File> getFiles(String path,List<File> files,boolean isLower,String extension){
		if(z.isNull(files)) {
			files = new ArrayList<File>();
		}
		//获取本级目录所有文件与文件夹对象
		File dir = new File(path);
		File[] filesArray = dir.listFiles();
		//如果本级目录没有文件与文件夹，直接返回
		if (filesArray == null)
			return files;
		for (int i = 0; i < filesArray.length; i++) {
			//判读是否查找下级目录
			if (filesArray[i].isDirectory() && isLower) {
				getFiles(filesArray[i].getAbsolutePath(),files,isLower,extension);
			} else {
				//判读是否是目录
				if (!filesArray[i].isDirectory()) {
					//当前文件名
					String nowFileName = filesArray[i].getAbsolutePath().toLowerCase();
					//查找指定扩展名文件
					if(z.isNotNull(extension)) {
						if(!".".equals(extension.substring(0, 1))) {
							extension = "."+extension;
						}
						String nowFileExtension = nowFileName.substring(nowFileName.length()-extension.length());
						//如果当前文件扩展名与查找目标扩展名相同，加入到返回结果
						if(nowFileExtension.equals(extension)) {
							files.add(filesArray[i]);
						}
					}else {
						files.add(filesArray[i]);
					}
				}
			}
		}
		return files;
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public static boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	/**
	 * 删除文件与子目录文件
	 * @param file
	 * @return
	 */
	public static boolean deletes(File file){
        if(file.isFile()){
            file.delete();
            return true;
        }
        File[] files = file.listFiles();
        for (File file1 : files) {
            if(file1 != null){
                if(file1.isFile()){
                    file1.delete();
                }else{
                    deletes(file1);
                }
            }
        }
        file.delete(); // 删除剩余空文件夹
        return true;
    }
	
	/**
	 * 删除目录中指定文件
	 * @param extension 文件扩展名
	 * @return
	 */
	public static int removeDirFile(File dir,String extension) {
		int removeNum = 0;
		if (dir.isDirectory() && z.isNotNull(extension)) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				if(!".".equals(extension.substring(0, 1))) {
					extension = "."+extension;
				}

				File f = new File(dir, children[i]);
				String nowFileName = f.getAbsolutePath().toLowerCase();
				String nowFileExtension = nowFileName.substring(nowFileName.length()-extension.length());
				//如果当前文件扩展名与查找目标扩展名相同，加入到返回结果
				if(nowFileExtension.equals(extension)) {
					//删除文件
					f.delete();
					removeNum = removeNum+1;
				}

			}
		}
		return removeNum;
	}

	/**
	 * 清空目录
	 * @param dir
	 * @return
	 */
	public static boolean clearDir(File dir) {
		boolean result = true;
		if (dir.isDirectory()) {
			String[] children = dir.list();
			// 递归删除目录中的子目录下
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					result = false;
				}
			}
		}else {
			result = false;
		}
		return result;
	}


	/**
	 * 移动文件
	 * 
	 * @param Path
	 *            文件
	 */
	public static void moveFile(String Path, String toPath) {
		// File (or directory) to be moved 
		File file = new File(Path); 

		// Destination directory 
		File dir = new File(toPath); 

		// Move file to new directory 
		file.renameTo(new File(dir, file.getName())); 
	}

	/**
	 * 复制单个文件
	 * @param oldPath String 原文件路径如：c:/fqf.txt
	 * @param newPath String 复制后路径如：f:/fqf.txt
	 */
	public static void copyFile(String oldPath, String newPath)
	{
		try
		{
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists())
			{
				//文件存在时
				InputStream inStream = new FileInputStream(oldPath); //读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ( (byteread = inStream.read(buffer)) != -1)
				{
					bytesum += byteread; //字节数文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void copyFile(File resource, File target) throws Exception {
		// 输入流 --> 从一个目标读取数据
		// 输出流 --> 向一个目标写入数据

		long start = System.currentTimeMillis();

		// 文件输入流并进行缓冲
		FileInputStream inputStream = new FileInputStream(resource);
		BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

		// 文件输出流并进行缓冲
		FileOutputStream outputStream = new FileOutputStream(target);
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

		// 缓冲数组
		// 大文件 可将 1024 * 2 改大一些，但是 并不是越大就越快
		byte[] bytes = new byte[1024 * 2];
		int len = 0;
		while ((len = inputStream.read(bytes)) != -1) {
			bufferedOutputStream.write(bytes, 0, len);
		}
		// 刷新输出缓冲流
		bufferedOutputStream.flush();
		//关闭流
		bufferedInputStream.close();
		bufferedOutputStream.close();
		inputStream.close();
		outputStream.close();

		long end = System.currentTimeMillis();

	}


	/**
	 * 复制文件夹
	 * @throws Exception 
	 */
	public static void copyFolder(String resource, String target) throws Exception{
		File resourceFile = new File(resource);
		if (!resourceFile.exists()) {
			throw new Exception("源目标路径：[" + resource + "] 不存在...");
		}
		File targetFile = new File(target);
		if (!targetFile.exists()) {
			throw new Exception("存放的目标路径：[" + target + "] 不存在...");
		}

		// 获取源文件夹下的文件夹或文件
		File[] resourceFiles = resourceFile.listFiles();

		for (File file : resourceFiles) {

			File file1 = new File(targetFile.getAbsolutePath() + File.separator + resourceFile.getName());
			// 复制文件
			if (file.isFile()) {
				// 在 目标文件夹（B） 中 新建 源文件夹（A），然后将文件复制到 A 中
				// 这样 在 B 中 就存在 A
				if (!file1.exists()) {
					file1.mkdirs();
				}
				File targetFile1 = new File(file1.getAbsolutePath() + File.separator + file.getName());
				copyFile(file, targetFile1);
			}
			// 复制文件夹
			if (file.isDirectory()) {// 复制源文件夹
				String dir1 = file.getAbsolutePath();
				// 目的文件夹
				String dir2 = file1.getAbsolutePath();
				copyFolder(dir1, dir2);
			}
		}
	}

	/**
	 * 获得指定文件的byte数组
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytes(File file) throws IOException {
		FileChannel fc = null;
		try {
			fc = new RandomAccessFile(file, "r").getChannel();
			MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,fc.size()).load();
			byte[] result = new byte[(int) fc.size()];
			if (byteBuffer.remaining() > 0) {
				byteBuffer.get(result, 0, byteBuffer.remaining());
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				fc.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获得指定文件的byte数组
	 * @throws IOException 
	 */
	public static byte[] getBytes(String filePath) throws IOException {
		return getBytes(new File(filePath));
	}


	/**
	 * 根据byte数组，生成文件
	 */
	public static void getFile(byte[] bfile, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		try {
			File dir = new File(filePath);
			if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
				dir.mkdirs();
			}
			file = new File(filePath + "\\" + fileName);
			fos = new FileOutputStream(file);
			bos = new BufferedOutputStream(fos);
			bos.write(bfile);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}


	/**
	 * 文件上传
	 * @param filename 文件名
	 * @param file  文件流
	 * @return
	 */
	public static String UploadFile(String filename, InputStream file) {
		String url = "";
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			String serverurl = z.sp.get("fileserverurl");
			HttpPost httppost = new HttpPost(serverurl+"/upload?filepath="+z.newNumber()+"&return_url_head="+StringUtil.UrlEncode(serverurl));
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			
			builder.addBinaryBody("cms_img", file, ContentType.create("multipart/form-data"), StringUtil.UrlEncode(filename));
			HttpEntity httpEntity = builder.build();
			httppost.setEntity(httpEntity);

			//创建返回信息处理类
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
				public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
					String resultURL = "";
					//获取请求状态
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						//如果返回信息不为空，直接输出。
						String Resultjson =  entity != null ? EntityUtils.toString(entity,"utf-8"):"";
						if(!"".equals(Resultjson) && Resultjson!=null) {
							Result result = JsonUtil.getObject(Resultjson, Result.class);
							if(result.code.equals(Code.SUCCESS)) {
								resultURL = String.valueOf(result.getData());
							}else {
								z.Error("HTTP ERROR : " + result.code+" | "+result.getMsg());
							}
						}
					} else {
						z.Error("HTTP ERROR : " + status);

					}
					return resultURL;
				}
			};
			url = httpclient.execute(httppost, responseHandler);
		} catch (Exception e) {
			z.Error("HTTP ERROR : " , e);
		}

		return url;
	}

	/**
	 * 创建文件存储目录
	 * @param filepath
	 * @return
	 * @throws Exception
	 */
	public static String CreateFileSavePath(String filepath) throws Exception{
		String fileSavePath = "";
		String project_path = System.getProperty(z.sp.get("webAppRootKeyValue"));
		if(!"".equals(project_path) && project_path!=null) {
			fileSavePath = project_path;
			//判读路径是否为空
			if(!"".equals(filepath) && filepath!=null) {
				fileSavePath = fileSavePath+"/files/"+filepath;
			}

			// 判断文件目录是否存在如果不存在怎么创建
			File dir = new File(fileSavePath);
			if (!dir.exists() && !dir.isDirectory()) {
				//创建多级目录
				dir.mkdirs();
			}
		}else {
			throw new Exception("文件服务器系统错误:创建文件保存路径出错");
		}
		return fileSavePath;
	}

}
